package cn.lijiajia3515.cairo.auth.modules.role;

import cn.lijiajia3515.cairo.core.exception.UnknownBusinessException;
import cn.lijiajia3515.cairo.core.page.Page;
import cn.lijiajia3515.cairo.security.oauth2.jwt.CairoJwtPrincipal;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Optional;

/**
 * Role Api
 */
@RestController
@RequestMapping("/api/role")
public class RoleApi {
	private final RoleService roleService;

	public RoleApi(RoleService roleService) {
		this.roleService = roleService;
	}

	// Operate
	@PostMapping("/save")
	@PreAuthorize("hasAnyAuthority('scp_save:role')")
	public RoleV2 save(@AuthenticationPrincipal CairoJwtPrincipal principal, @RequestBody SaveRoleParam param) {
		return roleService.save(principal.getAppId(), param);
	}

	@PutMapping("/modify")
	@PreAuthorize("hasAnyAuthority('scp_modify:role')")
	public RoleV2 modify(@AuthenticationPrincipal CairoJwtPrincipal principal, @RequestBody ModifyRoleParam param) {
		return roleService.modify(principal.getAppId(), param).orElseThrow(() -> new UnknownBusinessException("id not found"));
	}

	@DeleteMapping("/delete")
	@PreAuthorize("hasAnyAuthority('scp_delete:role')")
	public List<RoleV2> delete(@AuthenticationPrincipal CairoJwtPrincipal principal, @RequestBody DeleteRoleParam param) {
		return roleService.delete(principal.getAppId(), param);
	}

	// find
	@PostMapping("/find")
	@PreAuthorize("hasAnyAuthority('scp_find:role')")
	public List<Role> find(@AuthenticationPrincipal CairoJwtPrincipal principal, @RequestBody FindRoleParam param) {
		return roleService.find(principal.getAppId(), param);
	}

	@PostMapping("/find_page")
	@PreAuthorize("hasAnyAuthority('scp_find:role')")
	public Page<Role> findPage(@AuthenticationPrincipal CairoJwtPrincipal principal, @RequestBody FindRoleParam param) {

		return roleService.findPage(principal.getAppId(), param);
	}

	@GetMapping("/find/id/{id}")
	@PreAuthorize("hasAnyAuthority('scp_find:role')")
	public Optional<RoleV2> find(@AuthenticationPrincipal CairoJwtPrincipal principal, @PathVariable String id) {
		return roleService.findByCode(principal.getAppId(), id);
	}

}
